package cn.schoolwow.flow.monitor.module.common.flow;

import cn.schoolwow.ams.domain.block.list.clazz.ClazzListBlockOption;
import cn.schoolwow.ams.domain.block.list.dao.entityTable.EntityTableListBlockOption;
import cn.schoolwow.ams.module.block.listBlock.common.domain.remoteSelect.BlockRemoteSelect;
import cn.schoolwow.ams.module.block.listBlock.common.domain.remoteSelect.GetRemoteSelectOption;
import cn.schoolwow.ams.module.block.listBlock.common.domain.remoteSelect.RemoteSelectOption;
import cn.schoolwow.flow.monitor.domain.FlowMonitorOption;
import cn.schoolwow.flow.monitor.entity.FlowLog;
import cn.schoolwow.quickdao.domain.database.dql.condition.Condition;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;

import java.util.List;
import java.util.Map;

public class AddFlowCategoryNameRemoteSelectButton implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        EntityTableListBlockOption entityTableListBlockOption = flowContext.getInstanceData(EntityTableListBlockOption.class);
        ClazzListBlockOption clazzListBlockOption = flowContext.getInstanceData(ClazzListBlockOption.class);
        ApplicationContext applicationContext = flowContext.checkInstanceData(ApplicationContext.class);
        FlowMonitorOption flowMonitorOption = applicationContext.getBean(FlowMonitorOption.class);

        BlockRemoteSelect blockRemoteSelect = new BlockRemoteSelect("categoryName", "流程分类", new GetRemoteSelectOption() {
            @Override
            public List<RemoteSelectOption> getRemoteOption(Map<String, String> amsRemoteSelectMap) {
                String categoryName = amsRemoteSelectMap.get("name");
                Condition condition = flowMonitorOption.dao.query(FlowLog.class)
                        .distinct()
                        .addColumnAs("categoryName", "label")
                        .addColumnAs("categoryName", "value")
                        .limit(0,5);
                if(StringUtils.isNotBlank(categoryName)){
                    condition.addLikeQuery("categoryName", "%"+categoryName+"%");
                }
                List<RemoteSelectOption> remoteSelectOptionList = condition
                        .execute()
                        .getList(RemoteSelectOption.class);
                return remoteSelectOptionList;
            }
        });
        if(null!=entityTableListBlockOption){
            entityTableListBlockOption.remoteSelectList.add(blockRemoteSelect);
        }
        if(null!=clazzListBlockOption){
            clazzListBlockOption.remoteSelectList.add(blockRemoteSelect);
        }
    }

    @Override
    public String name() {
        return "添加流程分类远程下拉框搜索";
    }
}
